package top.gaui.nurse.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.*;

import top.gaui.nurse.entity.Nurse;
import top.gaui.nurse.entity.Patient;
import top.gaui.nurse.repository.PatientRepository;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;


/**
 * @author Fujie_Zeng
 * @version 1.0
 * @date 2020/4/7 21:37
 */
@RestController
@RequestMapping("/patient")
public class PatientHandler {
    @Autowired
    private PatientRepository patientRepository;

    @PostMapping({"/find/{name}/{department}/{page}/{size}","/find/{department}/{page}/{size}"})
    public  Page<Patient> findAllByName(@PathVariable(required = false)String name,@PathVariable String department,@PathVariable Integer page, @PathVariable Integer size) {
        Specification<Patient> specification = new Specification<Patient>() {
            @Override
            public Predicate toPredicate(Root<Patient> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                if (name !=null) {
                    predicateList.add(criteriaBuilder.like(root.get("name").as(String.class), "%"+ name+"%"));
                }
                if(department != null) {
                    predicateList.add(criteriaBuilder.equal(root.get("department").as(String.class),department));
                }

                Predicate[] pre = new Predicate[predicateList.size()];
                criteriaQuery.orderBy(criteriaBuilder.asc(root.get("inpatient")));
                return criteriaQuery.where(predicateList.toArray(pre)).getRestriction();
            }
        };
        PageRequest request = PageRequest.of(page-1,size);
        return patientRepository.findAll(specification, request);


    }

    @GetMapping("/findById/{inpatient}")
    public Optional<Patient> findById(@PathVariable("inpatient") Integer inpatient){
        return patientRepository.findById(inpatient);
    }
}
